package com.jymf.util;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @ClassName: SystemFilter
 * @Description: TODO
 * @author zyj
 * @date 2015-6-20 下午12:02:46
 */
public class SystemFilter extends HttpServlet implements Filter {

	/**
	 * @Fields serialVersionUID : TODO
	 */
	private static final long serialVersionUID = 1L;
	
	private FilterConfig config; 
	 /** 要检查的 session 的名称 */
    private String sessionKey;
     
    private static Set<String> noLoginURLList = new HashSet<String>();// 不用登陆就能访问的url
     
    /** 检查不通过时，转发的URL */
    private String forwardUrl;

    public void init(FilterConfig cfg) throws ServletException {
       this.config = cfg; 
       sessionKey = cfg.getInitParameter("sessionKey");
 
        String noLoginURL = cfg.getInitParameter("excepUrlRegex");
        if (null != noLoginURL && !"".equals(noLoginURL)) {
			String[] noLoginURLArr = noLoginURL.split(";");
			for (String o : noLoginURLArr) {
				noLoginURLList.add(o);
			}
		}
 
        forwardUrl = cfg.getInitParameter("redirectUrl");
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	
       HttpServletRequest request = (HttpServletRequest) req;
       HttpServletResponse response = (HttpServletResponse) res;
       
       String servletPath = request.getServletPath();
       Object sessionObj = request.getSession().getAttribute(sessionKey);
		String type = request.getHeader("X-Requested-With")==null?"":request.getHeader("X-Requested-With");
       String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort();

        String url = ((HttpServletRequest) req).getContextPath();
       // 如果请求的路径与forwardUrl相同，或请求的路径是排除的URL时，则直接放行
       if(this.matchUrl(servletPath)){
    	   chain.doFilter(req, res);
       }else if(this.officalPre(servletPath)){
		   chain.doFilter(req, res);
	   }else if (SessionUtil.LoginBack(noLoginURLList, servletPath)){
            chain.doFilter(req, res);
       }else if (sessionObj == null) {
    	   // 如果Session为空，则跳转到指定页面
		   if(type!=null&&"XMLHttpRequest".equals(type)){
				//ajax请求
			   response.setHeader("SESSIONSTATUS", "TIMEOUT");
			   response.setHeader("CONTEXTPATH", basePath+forwardUrl);
			   response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		   }else{
			   response.sendRedirect(basePath+forwardUrl);
		   }

    	   return;
       } else {
            chain.doFilter(req, res);//继续请求
       }
	}
	
	/**
	 * 匹配链接内容中的图片,css,js
	 * 
	 * @param str
	 *            ：资源路径
	 * @return true:是静态资源;false:非静态资源
	 */
	private boolean matchUrl(String str) {
		String regEx = ".*\\.jpeg$|.*\\.jpg$|.*\\.png$|.*\\.gif$|.*\\.css$|.*\\.js$|.*\\.icon|.*\\.svg|.*\\.eot|.*\\.ttf" +
				"|.*\\.woff|.*\\.woff2|.*\\.otf|.*\\.html";
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(str);
		while (mat.find()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 官网页面
	 * @param str
	 * @return: boolean 
	 * @date: 2015-7-9 下午10:44:31
	 * @author zyj
	 */
	private boolean officalPre(String str){
		String regEx = "/offical";
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(str);
		if (mat.find()) {
			return true;
		}
		return false;
		
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		 this.config = null;
	}

	
}
